from PIL import Image
def letterbox_image(image, size,modes,bbox):
    # 对图片进行resize，使图片不失真。在空缺的地方进行padding
    iw, ih = image.size
    w, h = size
    scale = min(w/iw, h/ih)
    nw = int(iw*scale)
    nh = int(ih*scale)

    image = image.resize((nw,nh), Image.BICUBIC)
    new_image = Image.new(modes, size, (128,128,128))
    new_image.paste(image, ((w-nw)//2, (h-nh)//2))
    # bbox: xmin, ymin, xmax, ymax
    for i in range(4): bbox[i] = bbox[i] * scale  # 与缩放因子相乘
    top = (h - nh) // 2
    bbox[1] = int(bbox[1] + top)
    bbox[3] = int(bbox[3] + top)
    bottom = h - nh - top
    left = (w - nw) // 2
    bbox[0] = int(bbox[0] + left)
    bbox[2] = int(bbox[2] + left)
    print(bbox)
    print(new_image.size)
    return new_image

img = Image.open(r"G:\01工作空间\pound_sufuce\pound_sufuce\SegmentationObject\404628897947189248-17.tif")
new_image = letterbox_image(img,[512,512],'P',[31,139,76,182])
new_image.show()
new_image.save(r"C:\Users\1\Desktop\hor4046.tif")